<?php
namespace Company\Controller;
use Think\Controller;
//外部接口
class ApieditController extends Controller {
    public function _initialize(){
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }

	//导单数据统计
	public function inbound_nums(){
		$datas=file_get_contents('php://input');
		file_put_contents('./log/checkstockinfo.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		// $datas='{"warehouse_code":"11330213","manua_id":["W29916000086","AO201706211413","MT20170622","TZ201706281719","TW201707190001","YZ201710130001","ZY201708030001"]}';
		$param=json_decode($datas,true);
		if(empty($param)){
			alert_json(0,'没有传输数据！');
		}
		$u=M('User');
		$w=M('Warehouse');
		$uw=M('UserWarehouse');
		$warehouse_code=$param['warehouse_code'];
		// $warehouse_code='12345678';
		$warehouse_id=$w->where(array('warehouse_code'=>$warehouse_code))->getField('id');
		$sql="SELECT * FROM  ".C('DB_PREFIX')."user_warehouse WHERE warehouse_group_id REGEXP '^".$warehouse_id."$|,".$warehouse_id."$|^".$warehouse_id.",|[,]".$warehouse_id."[,]'";
		$uw_list=M()->query($sql);

		// $time=time()-3600*24*2;//两天前
		$time=$param['time'];//当前时间
		$time_today=date("Y-m-d",$time);//今天
		$time_nextday=date("Y-m-d",$time+3600*24);//明天
		
		$str_time_today=strtotime($time_today);//今天(时间戳)
		$str_time_nextday=strtotime($time_nextday);//明天(时间戳)
		
		//当日导单数量-begin
		$list=array();
		$sql_database="show databases";
		$database_list=M()->query($sql_database);
		foreach($uw_list as $k=>$v){
			$map_u=array();
			$map_u['id']=$v['user_id'];
			$u_info=$u->where($map_u)->find();
			$username=$u_info['username'];
			$db_name=C('DB_PREFIX_T').$username;
			foreach($database_list as $ks=>$vs){
				if($vs["Database"]==$db_name){
					C('db_config.DB_NAME',$db_name);
					$po=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));
					$pog=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));
					$map=array();
					if($param['delete']==1){
						$map['_string']="po.add_time>$str_time_today and po.add_time<$str_time_nextday and status=-1";
					}else{
						$map['_string']="po.add_time>$str_time_today and po.add_time<$str_time_nextday and status=1";
					}
					$goods_list=$po->alias('po')->join('__PUSHORDERGOODS__ g on po.id=g.order_id')->where($map)->group('g.goods_no')->order('po.id')->getField('g.goods_no,g.goods_name,sum(g.goods_nums) sum_goodsnums');
					if(!empty($goods_list)){
						$list=array_merge($list,$goods_list);
					}
					continue;
				}
			}
		}
		//当日导单数量-end
		if(!empty($list)){
			alert_json(1,$list);
		}else{
			alert_json(0,"没有数据");
		}
	}
	//盘库信息接收
	public function checkstockinfo(){
		$datas=file_get_contents('php://input');
		file_put_contents('./log/checkstockinfo.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param=json_decode($datas,true);
		if(empty($param)){
			alert_json(0,'没有传输数据！');
		}
		$erp_code=$param['erp_code'];
		$order_no=$param['order_no'];
		
		$u=M('User');
		$map['id']=$erp_code;
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$m=M('CheckstockInfo',C('DB_PREFIX_T'), C('db_config'));
		$n=M('Checkstock',C('DB_PREFIX_T'), C('db_config'));
		$n_id=$n->where(array('order_no'=>$order_no))->getField('id');
		foreach($param['detail'] as $k=>$v){
			$data[$k]['manua_id']=$v['manua_id'];
			$data[$k]['source_no']=$v['source_no'];
			$data[$k]['goods_name']=$v['goods_name'];
			$data[$k]['goods_no']=$v['goods_no'];
			$data[$k]['goods_spec']=$v['goods_spec'];
			$data[$k]['amount']=$v['amount'];
			$data[$k]['bar_code']=$v['bar_code'];
			$data[$k]['conforming_p']=$v['conforming_p'];
			$data[$k]['nonconforming_p']=$v['nonconforming_p'];
			$data[$k]['scrap_one']=$v['scrap_one'];
			$data[$k]['check_scrap_one']=$v['check_scrap_one'];
			$data[$k]['check_nonconforming_p']=$v['check_nonconforming_p'];
			$data[$k]['check_conforming_p']=$v['check_conforming_p'];
			$data[$k]['check_amount']=$v['check_amount'];
			$data[$k]['remark']=$v['remark'];
			$data[$k]['order_id']=$n_id;
		}
		$res=$m->addAll($data);
		if(!$res){
			$return['message']='添加失败!';
            $return['status']=0; 
			$this->ajaxReturn($return);
		}else{
			$return['message']='添加成功!';
            $return['status']=1; 
			$this->ajaxReturn($return);
		}
	}
	//账册产品同步
	//erp_code:货主erp_code
	public function sys_product_info($user_code,$sn,$erp_code,$warehouse_code,$twice=0){
		$map['user_code']=$user_code;
		$u=M('User');
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$p=M('Product',C('DB_PREFIX_T'), C('db_config'));

		$p_info=$p->where(array('goods_no'=>$sn))->find();
		if(empty($p_info)){
			alert_json(0,'没有此料号商品信息');
		}
		// echo $p->_sql();
		
		//同步账册到主erp
		$zhu_erpcode=$u->where(array('id'=>$erp_code))->getField('erp_code');
		$username=$u->where(array('id'=>$zhu_erpcode))->getField('username');
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$po=M('Product',C('DB_PREFIX_T'), C('db_config'));
		$po_info=$po->where(array('goods_no'=>$p_info['goods_no']))->find();
		if($twice==1){//修改
			$update_data=array();
			$update_data['name']=$p_info['name'];
			$update_data['price']=$p_info['price'];
			$update_data['price_t']=$p_info['price_t'];
			$update_data['unit']=$p_info['unit'];
			$update_data['unit_t']=$p_info['unit_t'];
			$update_data['unit_no']=$p_info['unit_no'];
			$update_data['unit_t_goods_spec']=$p_info['unit_t_goods_spec'];
			$update_data['unit_no_t']=$p_info['unit_no_t'];
			$update_data['hs_code']=$p_info['hs_code'];
			$update_data['standard']=$p_info['standard'];
			$update_data['currency']=$p_info['currency'];
			$update_data['country']=$p_info['country'];
			$update_data['zccode']=$p_info['zccode'];
			$update_data['examined']=$p_info['examined'];
			$update_data['country_code']=$p_info['country_code'];
			$update_data['coin_code']=$p_info['coin_code'];
			$update_data['net_weight']=$p_info['net_weight'];
			$update_data['gross_weight']=$p_info['gross_weight'];
			$update_data['goods_tax']=$p_info['goods_tax'];
			$update_data['sell_price']=$p_info['sell_price'];
			$update_data['warehouse_code']=$p_info['warehouse_code'];
			$update_data['purchase_price']=$p_info['purchase_price'];
			$update_data['tariff_rate']=$p_info['tariff_rate'];
			$update_data['consumption_rate']=$p_info['consumption_rate'];
			$update_data['increment_rate']=$p_info['increment_rate'];
			$update_data['discount_rate']=$p_info['discount_rate'];
			$update_data['item_no']=$p_info['item_no'];
			$update_data['item_type']=$p_info['item_type'];
			$res=$po->where(array('goods_no'=>$p_info['goods_no']))->save($update_data);
		}else{
			// echo $po->_sql();
			if(!empty($po_info)){
				alert_json(0,'数据已存在！');
			}
			unset($p_info['id']);
			$res=$po->add($p_info);
		}
		if($res===false){
			alert_json(0,'失败');
		}else{
			if($twice==1){
				$push_data['product_id']=$po_info['id'];
				$push_data['twice']=1;
			}else{
				$p_info['id']=$res;//主erp的goods_id
			}
			$push_data['erp_code']=$zhu_erpcode;
			$push_data['warehouse_code']=$warehouse_code;
			$push_data['list']=$p_info;
			$push_wms_url="http://www.t-cang.com/wmstest/index.php?s=/Pushreceiveapi/booksinfoOrder";//仓库账册
			$push_res=push($push_wms_url,$push_data);
			$push_res=json_decode($push_res,true);
			
			if(!$push_res['status']){
				alert_json(0,'同步数据到仓库失败');
			}
			alert_json(1,'成功');
		}
	}
	//oms商品审核后接收信息（产品审核后回调地址）
	public function receive_product_info(){
		$datas=I('param.','','trim');
		file_put_contents('./log/receive_product_info.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
				// $datas=array (
  // 'is_confirm' => '1',
  // 'user_code' => 'AO20170621',
  // 'type' => '2',
  // 'goods_name' => 'asdsadasdsad',
  // 'goods_sn' => 'AO2017062112345699',
  // 'source_no' => '123456',
  // 'apply_price' => '0.8',
  // 'tariff_rate' => '0.8',
  // 'consumption_rate' => '0.8',
  // 'increment_rate' => '0.8',
  // 'discount_rate' => '0.7000',
  // 'remark' => '',
// );
		$param=$datas;
		if(empty($param)){
			alert_json(0,'没有传输数据！');
		}
		if(empty($param['is_confirm'])){
			alert_json(0,'没有传输is_confirm！');
		}
		if(empty($param['apply_price'])){
			alert_json(0,'没有传输apply_price！');
		}
		if(empty($param['tariff_rate'])){
			alert_json(0,'没有传输tariff_rate！');
		}
		if(empty($param['consumption_rate'])){
			alert_json(0,'没有传输consumption_rate！');
		}
		if(empty($param['increment_rate'])){
			alert_json(0,'没有传输increment_rate！');
		}
		if(empty($param['discount_rate'])){
			alert_json(0,'没有传输discount_rate！');
		}
		if(empty($param['user_code'])){
			alert_json(0,'没有传输user_code！');
		}
		if(empty($param['goods_sn'])){
			alert_json(0,'没有传输goods_sn');
		}
		// $param=array (
		  // 'user_code' => 'AO20170621',
		  // 'goods_name' => '★zg〓澳洲Nu-Lax乐康膏500g bs',
		  // 'goods_sn' => 'AO201706218712930110040',
		  // 'source_no' => '8712930110040',
		  // 'apply_price' => '111.0000',
		  // 'tariff_rate' => '0.0000',
		  // 'consumption_rate' => '0.0000',
		  // 'increment_rate' => '0.1700',
		  // 'discount_rate' => '0.7000',
		  // 'is_confirm' => '1',
		  // 'remark' => '',
		// );
		// dump($param);
		// die;
		$examined=$param['is_confirm'];//is_confirm 1:审核成功4：审核失败
		if($examined==4){
			$data['examined']=3;
		}
		if($examined==1){
			$data['examined']=2;
			$data['price']=$param['apply_price'];//申报价
			$data['tariff_rate']=$param['tariff_rate'];
			$data['consumption_rate']=$param['consumption_rate'];
			$data['increment_rate']=$param['increment_rate'];
			$data['discount_rate']=$param['discount_rate'];
			$data['item_no']=$param['item_no'];
			$data['item_type']=$param['item_type'];
		}
		$map['user_code']=$param['user_code'];
		// $map['user_key']=$param['user_key'];
		$u=M('User');
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$p=M('Product',C('DB_PREFIX_T'), C('db_config'));
		// dump($p);
		// die;
		$map_p['goods_no']=$param['goods_sn'];
		$res=$p->where($map_p)->save($data);
		// echo $p->_sql();
		// die;
		$warehouse_code='11330213';
		if($res!==false){
			if($param['type']==1){//新增
				$this->sys_product_info($param['user_code'],$param['goods_sn'],$u_info['id'],$warehouse_code);
			}
			if($param['type']==2){//修改
				$this->sys_product_info($param['user_code'],$param['goods_sn'],$u_info['id'],$warehouse_code,1);
			}
			$return['status']=1;
			$return['message']='成功';
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['message']='失败';
			$this->ajaxReturn($return);
		}
	}
	//抓单系统扣库存
	private function freez_storage($username,$goods_list){
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$m=M('StorageConfigElectricbusiness',C('DB_PREFIX_T'), C('db_config'));
		$trans=M('',C('DB_PREFIX_T'),C('db_config'));
		$trans->startTrans();   // 开启事务
		foreach($goods_list as $k=>$v){
			$map=array();
			$map['goods_no']=$v['goods_no'];
			$storage_amount_config=$m->where($map)->getField('storage_amount_config');
			$data['storage_amount_config']=$storage_amount_config-$v['goods_nums'];
			if($data['storage_amount_config']<0){
				$trans->rollback();
				return 2;
			}							
			$res=$m->where($map)->save($data);
			if($res===false){
				$trans->rollback();
				return 0;
			}
		}
		$trans->commit();
		return 1;
	}
	//对接抓单系统订单接收
	public function receive_pushorder(){
		$data	=	file_get_contents("php://input");
		if(empty($data)){
			$param=I('param.','','trim');
			file_put_contents('./log/receive_pushorder.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		}else{
			$param=json_decode($data,true);
			file_put_contents('./log/receive_pushorder.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		}
		// $param='{"appid":"yongzhuo","appsecret":"yongzhuo","order_list":[{"order_no":"505534964352870606","user_name":"朱晓明","user_phone":"18624290049","user_idcard":"211224199204227526","province":"天津","city":"天津市","area":"西青区","user_address":"天津 天津市 西青区 津来公路理工大学青年教师学者公寓3-2-302","buyer_name":"朱晓明","buyer_idcard":"211224199204227526","goods":[{"goods_name":"婴儿安全别针彩色别针大号6个卡装+小号9个卡装 新老包装随机发货","bar_code":"10881+10882","goods_price":33.12,"goods_nums":"1"}]},{"order_no":"505534800148046255","user_name":"李小慧","user_phone":"13175810215","user_idcard":"360502198506190023","province":"江西省","city":"萍乡市","area":"安源区","user_address":"江西省 萍乡市 安源区 萍乡经济开发区洪山大道蓝盾车辆检测站门卫处机动车查验室","buyer_name":"李小慧","buyer_idcard":"360502198506190023","goods":[{"goods_name":"贝亲奶嘴 自然实感宽口径硅胶奶嘴【2个装】S/M/L/LL*2","bar_code":"BA57+BA58 /BA58+BA59/BA59*2/","goods_price":43.92,"goods_nums":"1"}]}]}';
		// $param=json_decode($param,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }

		$map['appid']=$param['appid'];
		$map['appsecret']=$param['appsecret'];
		
		if(empty($param['appid'])){
			alert_json(0,'appid不能为空');
		}
		if(empty($param['appsecret'])){
			alert_json(0,'appsecret不能为空');
		}
		
		$u=M('User');
		$username=$u->where($map)->getField('username');
		if(empty($username)){
			alert_json(0,"没有此用户");
		}						  
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		
		$trans=M('', C('DB_PREFIX_T'), C('db_config'));
		$trans->startTrans();// 开启事务
		$m=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));
		$p=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		
		$order_list=$param['order_list'];
		if(empty($param['order_list'])){
			alert_json(0,'order_list不能为空');
		}
		
		$data_p=array();
		$data_og=array();
		$print_order=array();
		
		$order_ids=array();
		foreach($order_list as $k=>$v){
			$serialNumber_first=$this->serialNumber('Pushorder',$db_name);
			//流水订单号-begin
			//流水单号兼容事务提交-begin
			// dump($serialNumber);
			$len=strlen($serialNumber_first);
			$ser_nums=intval($serialNumber_first);
			$int_len=strlen($ser_nums);
			$ser_nums=$ser_nums+$order_foreachcount;
			$str_nums="";
			for($j=0;$j<$len-$int_len;$j++){
				$str_nums.='0';
			}
			$serialNumber=$str_nums.$ser_nums;
			//流水单号兼容事务提交-end
			$serialNumber='P'.date("Ymd",time()).$serialNumber;//加上agent_id分销商id防止重复
			//流水订单号-end
			if(empty($v['order_no'])){
				$trans->rollback();
				alert_json(0,'order_no不能为空');
			}
			if(empty($v['user_name'])){
				$trans->rollback();
				alert_json(0,'user_name不能为空');
			}
			if(empty($v['user_phone'])){
				$trans->rollback();
				alert_json(0,'user_phone不能为空');
			}
			if(empty($v['user_idcard'])){
				$trans->rollback();
				alert_json(0,'user_idcard不能为空');
			}
			if(empty($v['province'])){
				$trans->rollback();
				alert_json(0,'province不能为空');
			}
			if(empty($v['city'])){
				$trans->rollback();
				alert_json(0,'city不能为空');
			}
			if(empty($v['area'])){
				$trans->rollback();
				alert_json(0,'area不能为空');
			}
			if(empty($v['user_address'])){
				$trans->rollback();
				alert_json(0,'user_address不能为空');
			}
			if(empty($v['buyer_name'])){
				$trans->rollback();
				alert_json(0,'buyer_name不能为空');
			}
			if(empty($v['buyer_idcard'])){
				$trans->rollback();
				alert_json(0,'buyer_idcard不能为空');
			}
			
			$data_p['order_no']=$serialNumber;//流水单号
			$data_p['old_order_no']="ERP".$v['order_no'];//原单号//加上agent_id分销商id防止重复
			$count_m=$m->where(array('old_order_no'=>$v['order_no']))->count();
			if($count_m>0){
				$trans->rollback();
				alert_json(0,$v['order_no'].'订单编号重复,编号已经存在！');
			}
			$push_data=array();
			$push_data['detail'][$k]['goods_detail_id']=$res_g;//商品详细id
			$push_data['detail'][$k]['goods_nums']=$data_og['goods_nums'];//数量
			$push_data['detail'][$k]['goods_no']=$data_og['goods_no'];//商品编码
			
			//$warehouse_code='12345678';
			$warehouse_code='11330213';
			$push_data['warehouse_code']=$warehouse_code;
			$push_data['goods_nums']=$data_og['goods_nums'];//数量
			$push_data['goods_no']=$data_og['goods_no'];//商品编码
			
			// $res_freez=$this->freez_storage($username,$push_data['detail']);
			// if($res_freez==0){
				// $trans->rollback();
				// alert_json(0,'扣库存失败');
			// }
			// if($res_freez==2){
				// $trans->rollback();
				// alert_json(0,'库存不足');
			// }
			
			$data_p['user_name']=$v['user_name'];
			$data_p['user_phone']=$v['user_phone'];
			$data_p['user_idcard']=$v['user_idcard'];
			$data_p['province']=$v['province'];
			$data_p['city']=$v['city'];
			$data_p['area']=$v['area'];
			$data_p['user_address']=$v['user_address'];
			$data_p['buyer_name']=$v['buyer_name'];
			$data_p['buyer_idcard']=$v['buyer_idcard'];
			$data_p['add_time']		= time();
			$data_p['order_erp']	= 1;//订单抓取系统
			
			$print_order['receiveMan']=$v['user_name'];
			$print_order['receiveManPhone']=$v['user_phone'];
			$print_order['receiveProvince']=$v['province'];
			$print_order['receiveCity']=$v['city'];
			$print_order['receiveCounty']=$v['area'];
			$print_order['receiveManAddress']=$v['user_address'];
			$print_order['order_no']=$serialNumber;
			$print_order['add_time']=time();//添加时间
			
			//添加面单
			$res_p=$p->add($print_order);
			if(!$res_p){
				$trans->rollback();
				alert_json(0,'添加面单数据失败');
			}
			//添加订单
			$insert_id=$m->add($data_p);
			if(!$insert_id){
				$trans->rollback();
				alert_json(0,'添加订单数据失败');
			}
			$order_ids[]=$insert_id;
			//添加订单详情
			foreach($v['goods'] as $ks=>$vs){
				if(empty($vs['bar_code'])){
					$trans->rollback();
					alert_json(0,'bar_code不能为空');
				}
				if(empty($vs['goods_price'])){
					$trans->rollback();
					alert_json(0,'goods_price不能为空');
				}
				if(empty($vs['goods_nums'])){
					$trans->rollback();
					alert_json(0,'goods_nums不能为空');
				}
				$data_og['bar_code']=$vs['bar_code'];
				$data_og['goods_price']=$vs['goods_price'];
				$data_og['goods_name']=$vs['goods_name'];
				$data_og['goods_no']=$vs['goods_no'];
				$data_og['goods_nums']=$vs['goods_nums'];
				$data_og['order_id']=$insert_id;
				$res_g=$g->add($data_og);
				if(!$res_g){
					$trans->rollback();
					alert_json(0,'添加订单详情失败');
				}
			}
		}
		// $ids=implode(",",$order_ids);
		
		$trans->commit();
		alert_json(1,'成功！');
	}
	//代销商商品价格、预警库存配置信息
	public function get_storage_config(){
		$datas=file_get_contents('php://input');
		file_put_contents('./log/get_storage_config.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param=json_decode($datas,true);

		$erp_code=$param['erp_code'];
		$goods_no=$param['goods_no'];
		$distribution_department_id=$param['distribution_department_id'];
		
		$u=M('User');
		$username=$u->where(array('id'=>$erp_code))->getField('username');
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		
		$s=M('StorageConfig',C('DB_PREFIX_T'), C('db_config'));
		$s_info=$s->where(array('goods_no'=>$goods_no,'distribution_department_id'=>$distribution_department_id))->find();
		file_put_contents('./log/get_storage_config.log',date('Y-m-d H:i:s').var_export($s->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
		if(empty($s_info)){
			$return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
		}else{
			$return['status']=1;
			$return['message']='查询成功';
			$return['data']=$s_info;
			$this->ajaxReturn($return);
		}
		
	}
	
	//分销商订单
	public function agent_pushorder(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/agent_pushorder.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql

		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		
		$erp_code=$param['erp_code'];
		$u=M('User');
		$username=$u->where(array('id'=>$erp_code))->getField('username');
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		
		$trans=M('', C('DB_PREFIX_T'), C('db_config'));
		$trans->startTrans();   // 开启事务
		$m=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));
		$p=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		$cb=M('Checkbill',C('DB_PREFIX_T'), C('db_config'));
		
		$order_list=$param['order_list'];
		
		$data_p=array();
		$data_og=array();
		$print_order=array();
		
		$order_ids=array();
		
		foreach($order_list as $k=>$v){
			$serialNumber_first=$this->serialNumber('Pushorder',$db_name);
			//流水订单号-begin
			//流水单号兼容事务提交-begin
			// dump($serialNumber);
			$len=strlen($serialNumber_first);
			$ser_nums=intval($serialNumber_first);
			$int_len=strlen($ser_nums);
			$ser_nums=$ser_nums+$order_foreachcount;
			$str_nums="";
			for($j=0;$j<$len-$int_len;$j++){
				$str_nums.='0';
			}
			$serialNumber=$str_nums.$ser_nums;
			//流水单号兼容事务提交-end
			$serialNumber='P'.$v['agent_id'].date("Ymd",time()).$serialNumber;//加上agent_id分销商id防止重复
			//流水订单号-end

			$data_p['order_no']=$serialNumber;//流水单号
			$data_p['old_order_no']="O".$v['agent_id'].$v['order_no'];//原单号//加上agent_id分销商id防止重复
			$data_p['user_name']=$v['user_name'];
			$data_p['user_phone']=$v['user_phone'];
			$data_p['user_idcard']=$v['user_idcard'];
			$data_p['province']=$v['province'];
			$data_p['city']=$v['city'];
			$data_p['area']=$v['area'];
			$data_p['user_address']=$v['user_address'];
			$data_p['buyer_name']=$v['buyer_name'];
			$data_p['buyer_idcard']=$v['buyer_idcard'];
			$data_p['agent_id']=$v['agent_id'];
			$data_p['add_time']		= time();
			
			$print_order['receiveMan']=$v['user_name'];
			$print_order['receiveManPhone']=$v['user_phone'];
			$print_order['receiveProvince']=$v['province'];
			$print_order['receiveCity']=$v['city'];
			$print_order['receiveCounty']=$v['area'];
			$print_order['receiveManAddress']=$v['user_address'];
			$print_order['order_no']=$serialNumber;
			$print_order['agent_id']=$v['agent_id'];
			$print_order['add_time']=time();//添加时间
			
			//添加面单
			$res_p=$p->add($print_order);
			if(!$res_p){
				$trans->rollback();
				alert_json(0,'添加面单数据失败');
			}
			//添加订单
			$insert_id=$m->add($data_p);
			if(!$insert_id){
				$trans->rollback();
				alert_json(0,'添加订单数据失败');
			}
			$order_ids[]=$insert_id;
			//添加订单详情
			foreach($v['goods'] as $ks=>$vs){
				$data_og['bar_code']=$vs['bar_code'];
				$data_og['goods_price']=$vs['goods_price'];
				$data_og['goods_no']=$vs['goods_no'];
				$data_og['goods_nums']=$vs['goods_nums'];
				$data_og['agent_id']=$vs['agent_id'];
				$data_og['order_id']=$insert_id;
				$res_g=$g->add($data_og);
				if(!$res_g){
					$trans->rollback();
					alert_json(0,'添加订单详情失败');
				}
			}
		}
		$ids=implode(",",$order_ids);
		$param['checkbill_list']['ids']=$ids;
		$param['checkbill_list']['pay_status']=1;
		unset($param['checkbill_list']['id']);
		//添加对账单
		$res_cb=$cb->add($param['checkbill_list']);
		if(!$res_cb){
			$trans->rollback();
			alert_json(0,'添加对账单失败');
		}
		$trans->commit();
		alert_json(1,'成功！');
	}
	//账册商品
	public function product_info(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/product_info.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		$erp_code=$param['erp_code'];
		$goods_no=$param['goods_no'];
		$agent_id=$param['agent_id'];
		$u=M('User');
		$u_info=$u->where(array('id'=>$erp_code))->find();
		$db_name=C('DB_PREFIX_T').$u_info['username'];
		C('db_config.DB_NAME',$db_name);
		
		$m=M('Product', C('DB_PREFIX_T'), C('db_config'));
		$s=M('StorageConfig', C('DB_PREFIX_T'), C('db_config'));
		$d=M('DistributionPeople');
		$distribution_department_id=$d->where(array('id'=>$agent_id))->getField('department_id');
		
		$m_info=$m->where(array('goods_no'=>$goods_no))->find();
		$price_config=$s->where(array('goods_no'=>$goods_no,'distribution_department_id'=>$distribution_department_id))->getField('price_config');
		
		$m_info['sell_price']=$price_config;
		
		file_put_contents('./log/product_info.log',date('Y-m-d H:i:s').json_encode($m_info).PHP_EOL,FILE_APPEND);//日志导出sql
		if(empty($m_info)){
			alert(0,0);
		}else{
			alert(1,json_encode($m_info));
		}
	}
	//订单备注同步
	public function pushorder_mark(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/pushorder_mark.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// $data='{"logistics_no":"C20170815156144","mark_mailno":"224433221","erp_code":"20"}';
		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		$u=M('User');
		$u_info=$u->field('username')->where(array('id'=>$param['erp_code']))->find();
		// echo $u->getlastsql();
		$db_name=C('DB_PREFIX_T').$u_info['username'];
		C('db_config.DB_NAME',$db_name);
		$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
		$res=$m->where(array('logistics_no'=>$param['logistics_no']))->save(array('mark_mailno'=>$param['mark_mailno']));
		// echo $m->getlastsql();
		// die;
		if($res!==false){
			$return['status']=1;
			$return['message']='成功';
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['message']='失败';
			$this->ajaxReturn($return);
		}
	}
	//税金提示
	public function alert_tax(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/alert_tax.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		$u=M('User');
		$m=M('Member');
		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		$map['user_code']=$param['user_code'];
		$member_id=$u->where($map)->getField('member_id');
		$data_m['oms_fee_status']=$param['tax_status'];
		$res=$m->where(array('id'=>$member_id))->save($data_m);
		if($res!==false){
			$return['status']=1;
			$return['message']='成功';
			$this->ajaxReturn($return);
		}else{
			$return['status']=1;
			$return['message']='失败';
			$this->ajaxReturn($return);
		}
	}
	//订单状态接口
	public function order_status(){
		$u=M('User');
		$data=file_get_contents("php://input");
		file_put_contents('./log/order_status'.date('Y-m-d').'.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// $data='[{"user_code":"AO20170621","order_no":"JY-2024659","apply_order_no":"C20170719138139","logistics_no":"50552940008922","is_pass":0,"is_deliver":0,"platform_name":"ERP","fail_reason":"feifeifeif"}]';
        $param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['order_no']='';
			$this->ajaxReturn($return);
        }
		foreach($param as $k=>$v){
			$user_code=$v['user_code'];
			// $user_key=$v['user_key'];
			$map['old_order_no']=$v['order_no'];
			$map['status']=1;
			$data_pushorder=array();
			$data_pushorder['apply_order_no']=$v['apply_order_no'];
			$data_pushorder['logistics_no']=$v['logistics_no'];
			$data_pushorder['is_pass']=$v['is_pass'];
			$data_pushorder['is_delivery']=$v['is_deliver'];
			$data_pushorder['fail_reason']=$v['fail_reason'];
			$data_pushorder['actual_weight']=$v['actual_weight'];//实际重量
			if(empty($v['deliver_time'])){
				$data_pushorder['delivery_time']=0;//出库时间
			}else{
				$data_pushorder['delivery_time']=$v['deliver_time'];//出库时间
			}
			
			$u_info=$u->field('username')->where(array('user_code'=>$user_code))->find();
			$db_name=C('DB_PREFIX_T').$u_info['username'];
			C('db_config.DB_NAME',$db_name);
			$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
			$res=$m->where($map)->save($data_pushorder);
			// echo $m->getlastsql();
			// die;
			$return[$k]['order_no']=$v['order_no'];
			if($res===false){
				$return[$k]['status']=0;
			}else{
				//推送分销商-begin
				$m_info=$m->field('order_erp,agent_id')->where($map)->find();
				// echo $m->getlastsql();
				// die;
				$agent_id=$m_info['agent_id'];
				if(!empty($agent_id)){
					// $agent_url="http://erpvr.jm.com/index.php/Agent/Api/order_status";//分销订单状态接口
					$agent_url="http://www.t-cang.com/erpts/index.php/Agent/Api/order_status";
					$data_pushorder['order_no']=substr($v['order_no'],-14);//原订单号
					$data_pushorder['agent_id']=$agent_id;
					$res_agent = push($agent_url,$data_pushorder);
					$res_agent=json_decode($res_agent,true);
					if(!$res_agent['status']){
						file_put_contents('./log/order_status_agent.log',date('Y-m-d H:i:s').var_export($res_agent,true).PHP_EOL,FILE_APPEND);//日志导出sql
					}
				}
				//推送分销商-end
				//推送订单收集系统-begin
				$order_erp=$m_info['order_erp'];
				if(!empty($order_erp)){
					$agent_url="http://192.168.0.8:8080/com.botao.erp.api/orderDetails/receiveData.do";//抓单订单状态接口
					// $agent_url="http://www.t-cang.com/erpts/index.php/Agent/Api/order_status";
					$data_pushorder_ss=array();
					$data_pushorder_ss['logisticsId']=$v['logiscompany_code'];//物流企业编号
					$data_pushorder_ss['logisticsName']=$v['logiscompany_name'];//物流单号
					$data_pushorder_ss['waybill']=$v['logistics_no'];//物流单号
					if(empty($v['deliver_time'])){
						$data_pushorder_ss['deliveryTime']=0;//出库时间
					}else{
						$data_pushorder_ss['deliveryTime']=$v['deliver_time'];//出库时间
					}
					$data_pushorder_ss['orderId']=$v['order_no'];//原订单号
					$res_agent = pushjava($agent_url,$data_pushorder_ss);
					dump($res_agent);
					die;
					$res_agent=json_decode($res_agent,true);
					if(!$res_agent['status']){
						file_put_contents('./log/order_status_agent.log',date('Y-m-d H:i:s').var_export($res_agent,true).PHP_EOL,FILE_APPEND);//日志导出sql
					}
				}
				//推送订单收集系统-end
				$return[$k]['status']=1;
			}
		}
		$this->ajaxReturn($return);
	}
	//推送云仓库存
	//$type--insert--edit--delete
	public function push_yungoods($id,$type){
		$username=session('company.username');
        $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
		
		if($type=="delete"){
			$map_ao['id']=array('in',$id);
			$ao_list=$ao->field('goods_no goods_sn')->where($map_ao)->select();
		}else{
			$map_ao['id']=$id;
			$ao_list=$ao->field('goods_name,price goods_price,receive_amount goods_number,goods_no goods_sn,source_no goods_pn,net_weight,gross_weight,3 is_cross,goods_tax g_tax')->where($map_ao)->find();
		}
		

		// echo $ao->getlastsql();
		$url=C('BASE_CONFIG.yuncang_goods');//云仓同步添加商品接口
		$token=C('BASE_CONFIG.yuncang_token');//云仓同步添加商品接口
		$push_list['warehouse_code']=session('company.warehouse_code');
		$push_list['token']=$token;
		$push_list['type']=$type;
		$push_list['data'][0]=$ao_list;
		// var_dump($push_list);
		$res = push($url,$push_list);
		if(!$res['status']){	//失败
			$return['status']=0;
			$return['message']='推送云仓数据失败，请重新推送';
			$this->ajaxReturn($return);
		}else{
			$ao->where($map_ao)->setField('push_yuncang_status',1);//更新推送状态
			$return['message']='添加成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
		}
    }
	//库存更新(按批次)
	//status:1-冻结2-出库3-退库4-入库
	public function update_goodsamount(){
		$data=file_get_contents("php://input");
		// file_put_contents('./log/update_goodsamount.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// die;
        $param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=false;
			$return['message']='操作有误';
			$this->ajaxReturn($return);
        }
		$warehouse_code=$param['warehouse_code'];
		$erp_code=$param['erp_code'];
		$status=$param['status'];
		$amount=$param['amount'];
		$id=$param['id'];
		$cloud_status=$param['cloud_status'];//是否云仓商品
		if(empty($id)){
			$return['status']=0;
			$return['info']="没有传输入库批次id";
			$this->ajaxReturn($return);
		}
		if(empty($erp_code)){
			$return['status']=0;
			$return['info']="没有传输企业编码";
			$this->ajaxReturn($return);
		}
		if(empty($warehouse_code)){
			$return['status']=0;
			$return['info']="没有传输仓库编码";
			$this->ajaxReturn($return);
		}
		if(empty($status)){
			$return['status']=0;
			$return['info']="没有传输更新状态参数";
			$this->ajaxReturn($return);
		}
		if(empty($amount)){
			$return['status']=0;
			$return['info']="没有传输数量";
			$this->ajaxReturn($return);
		}
		$username=M('user')->where("id=".$erp_code)->getField('username');
        $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);

		if($status==1){//当前操作为冻结状态
			$data_ao['freez_amount']=array('exp','freez_amount+'.$amount);//冻结数量
			$data_ao['storage_amount']=array('exp','storage_amount-'.$amount);//更新库存
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num+'.$amount);//冻结云仓数量
				$data_ao['cloud_storage_num']=array('exp','cloud_storage_num-'.$amount);//更新云仓库存
			}
		}
		if($status==2){//当前操作为出库状态
			$data_ao['freez_amount']=array('exp','freez_amount-'.$amount);//冻结数量
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num-'.$amount);//冻结数量
			}
		}
		if($status==3){//当前操作为退库状态
			$data_ao['freez_amount']=array('exp','freez_amount-'.$amount);//冻结数量
			$data_ao['storage_amount']=array('exp','storage_amount+'.$amount);//更新库存
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num-'.$amount);//冻结数量
				$data_ao['cloud_storage_num']=array('exp','cloud_storage_num+'.$amount);//更新库存
			}
		}
		// if($status==4){//当前操作为入库状态（仓库入库，erp要同步插入批次数据）
			
		// }
		$map_ao['id']=$id;//条件
		$map_ao['id']=$id;//条件
		$res_ao=$ao->where($map_ao)->save($data_ao);//更新
		if($res_ao){
			$return['status']=1;
			$return['info']="更新成功";
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['info']="更新批次库存失败";
			$this->ajaxReturn($return);
		}
	}
	//批次库存同步（仓库入库-erp则同步仓库批次入库信息）
	public function inbound_batch(){
		$data=file_get_contents("php://input");
		// file_put_contents('./log/inbound_batch.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// die;
        $param=json_decode($data,true);
		$return=array();
		if(!isset($param) || count($param)==0){
            $return['status']=false;
			$return['message']='操作有误';
			$this->ajaxReturn($return);
        }
		$data_ao['warehouse_code']=$param['warehouse_code'];
		$data_ao['goods_no']=$param['goods_no'];
		$data_ao['manual_id']=$param['manua_id'];
		$data_ao['batch_no']=$param['batch_no'];

		$data_ao['goods_sn']=trim($param['goods_no']).$param['warehouse_code'];//货号
		$data_ao['grounding_status']=0;
		
		$data_ao['old_arrival_id']=$param['id'];

		$data_ao['old_goods_id']=$param['old_goods_id'];
		$data_ao['overdue_time']=$param['overdue_time'];
		$data_ao['declare_unit']=$param['declare_unit'];
		$data_ao['unit1']=$param['unit1'];
		$data_ao['unit2']=$param['unit2'];
		$data_ao['goods_spec']=$param['goods_spec'];
		$data_ao['goods_cate']=$param['goods_cate'];
		$data_ao['storage_id']=$param['storage_id'];
		$data_ao['cloud_depot_status']=$param['cloud_depot_status'];
		$data_ao['cloud_num']=$param['cloud_num'];
		$data_ao['cloud_unit']=$param['cloud_unit'];
		$data_ao['add_time']=$param['add_time'];
		$data_ao['conforming_p']=$param['conforming_p'];
		$data_ao['nonconforming_p']=$param['nonconforming_p'];
		$data_ao['scrap_one']=$param['scrap_one'];
		$data_ao['scrap_two']=$param['scrap_two'];
		$data_ao['bar_code']=$param['bar_code'];
		$data_ao['currency']=$param['currency'];
		$data_ao['country_code']=$param['country_code'];
		$data_ao['price']=$param['price'];
		$data_ao['total_price']=$param['total_price'];
		$data_ao['amount']=$param['receive_amount'];
		$data_ao['receive_amount']=$param['receive_amount'];
		$data_ao['declare_amount']=$param['declare_amount'];
		$data_ao['storage_amount']=$param['storage_amount'];
		$data_ao['freez_amount']=$param['freez_amount'];
		
		$data_ao['goods_name']=$param['goods_name'];
		$data_ao['item_type']=$param['item_type'];
		$data_ao['item_no']=$param['item_no'];
		$data_ao['source_no']=$param['source_no'];
		
		$username=M('user')->where("id=".$param['erp_code'])->getField('username');
        $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
		$res=$ao->add($data_ao);
		if($res){
			$return['status']=false;
			$return['message']='添加成功';
			$this->ajaxReturn($return);
		}
		
	}
	///库存同步--接收wms推送过来的商品库存信息
    public function receive_synch_goods(){
        $data=file_get_contents("php://input");
		// file_put_contents('./log/receive_synch_goods.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// die;
        $data=json_decode($data,true);
		// dump($data);
		$return=array();
        if(!isset($data) || count($data)==0){
            $return['status']=false;
			$return['message']='操作有误';
			alert(0,$return);
        }
        
        $k=0;
        foreach($data as $k=>$v){
            $username=M('user')->where("id=".$v['erp_code'])->getField('username');
            $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
            $where['warehouse_code']=$v['warehouse_code'];
			$where['goods_no']=$v['goods_no'];
			$where['manua_id']=$v['manua_id'];
			foreach($v['goods_info_list'] as $ks=>$vs){//商品批次列表
				$where['batch_no']=$vs['batch_no'];
				$ao_info=$ao->where($where)->find();
				//要添加(更新的信息)
				
				$data_ao['warehouse_code']=$v['warehouse_code'];
				$data_ao['goods_sn']=trim($v['goods_no']).$v['warehouse_code'];//货号
				$data_ao['grounding_status']=0;
				
				$data_ao['old_arrival_id']=$v['id'];
				$data_ao['goods_no']=$v['goods_no'];
				$data_ao['manual_id']=$v['manua_id'];
				$data_ao['batch_no']=$vs['batch_no'];
				$data_ao['old_goods_id']=$vs['old_goods_id'];
				$data_ao['overdue_time']=$vs['overdue_time'];
				$data_ao['declare_unit']=$vs['declare_unit'];
				$data_ao['unit1']=$vs['unit1'];
				$data_ao['unit2']=$vs['unit2'];
				$data_ao['goods_spec']=$vs['goods_spec'];
				$data_ao['goods_cate']=$vs['goods_cate'];
				$data_ao['storage_id']=$vs['storage_id'];
				$data_ao['cloud_depot_status']=$vs['cloud_depot_status'];
				$data_ao['cloud_num']=$vs['cloud_num'];
				$data_ao['cloud_unit']=$vs['cloud_unit'];
				$data_ao['add_time']=$vs['add_time'];
				$data_ao['conforming_p']=$v['conforming_p'];
				$data_ao['nonconforming_p']=$v['nonconforming_p'];
				$data_ao['scrap_one']=$v['scrap_one'];
				$data_ao['scrap_two']=$v['scrap_two'];
				$data_ao['bar_code']=$vs['bar_code'];
				$data_ao['currency']=$vs['currency'];
				$data_ao['country_code']=$vs['country_code'];
				$data_ao['price']=$vs['price'];
				$data_ao['total_price']=$vs['total_price'];
				$data_ao['amount']=$vs['receive_amount'];
				$data_ao['receive_amount']=$vs['receive_amount'];
				$data_ao['declare_amount']=$vs['declare_amount'];
				$data_ao['storage_amount']=$vs['storage_amount'];
				$data_ao['freez_amount']=$vs['freez_amount'];
				
				$data_ao['goods_name']=$vs['goods_name'];
				$data_ao['item_type']=$vs['item_type'];
				$data_ao['item_no']=$vs['item_no'];
				$data_ao['source_no']=$vs['source_no'];
				
				if(empty($ao_info)){//添加（没有此商品库存信息，直接添加）
					$res=$ao->add($data_ao);
					// dump($ao);
					// echo $ao->getlastsql();
					if($res){
						$k++;
						continue;
					}else{
						$return['status']=false;
						$return['message']='成功'.$k.'个,批次号'.$vs['batch_no'].'添加出错';
						alert(0,$return);
					}
				}else{//编辑（没有此商品库存信息，直接覆盖对应字段）
					$res=$ao->where($where)->save($data_ao);
					if($res!==false){
						$k++;
						continue;
					}else{
						$return['status']=false;
						$return['message']='成功'.$k.'个,批次号'.$vs['batch_no'].'更新出错';
						alert(0,$return);
					}
				}
			}
        }
		$return['status']=true;
		$return['message']='全部成功，共'.$k.'个';
		alert(1,$return);
    }
    //////接收实收数据 ///////也需要根据不同的企业编码，将数据推入不同企业，目前只是推一个企业
    public function receivedData(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        /*$data=array(
            "info" => array(
                0 => array (
                    "old_purchasing_no" => "2017012011776450587660960",
                    "old_goods_id" =>"65",
                    "erp_code" =>  "1",
                    "receive_amount" => "12",
                ),
                 1 => array (
                    "old_purchasing_no" => "2017012011776450587660960",
                    "old_goods_id" =>"66",
                    "erp_code" =>  "1",
                    "receive_amount" => "12",
                )
            ),
            "depot_code" =>"12345",
        );*///测试数据
        if(!isset($data['info']) || count($data['info'])==0){
            alert(0,'操作有误');
        }
        $data=$data['info'];
        $return=array();
        $k=0;
        foreach($data as $k=>$v){
            $username=M('user')->where("id=".$v['erp_code'])->getField('username');
			$where['id']=$v['old_goods_id'];//这里是通过第一个接口发送过去的商品id  是唯一的，所以只需要找到对应数据库就能精确到唯一数据，不需要仓库编码
			
			if($v['bound_cate_code']=="PRO"){
				if($v['primarygoods_status']==1){
					$p=M('ProductOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
					$true=$p->where($where)->save(array('is_back_count'=>$v['receive_amount'],'is_back'=>1));
				}
				if($v['primarygoods_status']==2){
					$pr=M('ProductOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
					$p=M('ProductOrderByproduct',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
					$pr->where($where)->save(array('is_back'=>1));
					$true=$p->where($where)->save(array('is_back_count'=>$v['receive_amount'],'is_back'=>1));
				}
			}else{
				$p=M('list_product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
				$true=$p->where($where)->save(array('is_back_count'=>$v['receive_amount'],'is_back'=>1));
			}

            if($true){
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$v['erp_code'];
                $k++;
                $this-> massage('实收数据','实收数据回执','采购单中的产品(ID='.$where['id'].')已被回执，回执数量为'.$v['receive_amount'],$username);
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
    public function productExamin(){
        $data=file_get_contents("php://input");
		file_put_contents('./log/productExamin.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
        $data=json_decode($data,true);
        $k=0;
        $where['examined']=1;
        $return=array();
        foreach($data['info'] as $v){
            $username=M("user")->where(array('id'=>$v['erp_code']))->getField('username');
            $this->product=M('product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
			$where['goods_no']=$v['goods_no'];
            $where['zccode']=$v['manua_id'];
            $true=$this->product->where($where)->setField('examined',2);
            if($true){
                $k++;
                $this->massage('产品','产品审核','产品信息(ID='.$where['id'].')已经被审核通过',$username);
				$return[$where['id']]['goods_no']=$v['goods_no'];
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$v['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
    public function bookExamin(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $where['examined']=1;
        $k=0;
        foreach($data['info'] as $d){
            $erp_code=$d['erp_code'];
            $where['book_no']=$d['code'];
            $username=M("user")->where(array('id'=>$erp_code))->getField('username');
            $this->product=M('book',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
            $true=$this->product->where($where)->setField('examined',2);
            if($true){
                $k++;
                $this-> massage('账册','账册审核','账册信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['book_no']]['is_true']=$true;
                $return[$where['book_no']]['erp_code']=$d['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
    public function massage($type,$title,$detail,$username){
        $massage['url']='';
        $massage['type']=$type;
        $massage['title']=$title;
        $massage['detail']=$detail;
        M('massage',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username)->add($massage);
    }

    //////////////审核，审核之后 wms返回数量
    public function beforeShelves(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $k=0;
        foreach($data as $d){
            $erp_code=$d['erp_code'];
            $username=M("user")->where(array('id'=>$erp_code))->getField('username');
            $where['id']=$d['old_goods_id'];
            $where['is_examined']=0;
            $this->product=M('list_product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
            $true=$this->product->where($where)->setField('is_examined',1);
            if($true){
                $k++;
                $this-> massage('商品','商品审核','商品信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$d['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }

    //////////////wms上架（上架之后  ERP可以上架）
    public function beforeShelves_2(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $k=0;
		file_put_contents('./log/beforeShelves_2.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
       // $data=array (
			  // 0 => 
			  // array (
				// 'old_goods_id' => '130',
				// 'erp_code' => '1',
			  // ),
			// );
        foreach($data as $d){
            $erp_code=$d['erp_code'];
            $username=M("user")->where(array('id'=>$erp_code))->getField('username');
            $where['id']=$d['old_goods_id'];
            // $where['is_shelves']=1;
            $this->product=M('list_product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
			
            $true=$this->product->where($where)->setField('is_shelves',2);
            if($true){
                $k++;
                $this-> massage('商品','商品审核','商品信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$d['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
	
	//流水号
	public function serialNumber($tablename,$db_name){
		C('db_config.DB_NAME',$db_name);
		$m=M($tablename, C('DB_PREFIX_T'), C('db_config'));
		//当日流水号生成
		$map['_string']="add_time-UNIX_TIMESTAMP(DATE(NOW()))>0 and add_time-UNIX_TIMESTAMP(DATE(NOW()))<86400";
		$count=$m->where($map)->count();//当天添加的采购单数
		
		$count=$count+1;
		$serial_number="";
		if($count<10){
			$serial_number='0000'.strval($count);
		}
		if($count>=10 and $count<100){
			$serial_number='000'.$count;
		}
		if($count>=100 and $count<1000){
			$serial_number='00'.$count;
		}
		if($count>=1000 and $count<10000){
			$serial_number='0'.$count;
		}
		return $serial_number;//流水序号
	}
}